package com.example.support.redis;

import java.util.concurrent.TimeUnit;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;

import com.example.support.spring.SpringContextHolder;

public class RedisHelper {

	// ========== key ==========

	public static boolean exists(String key) {
		return SingletonHolder.stringRedisTemplate.hasKey(key);
	}

	public static boolean del(String key) {
		return SingletonHolder.stringRedisTemplate.delete(key);
	}

	public static boolean expire(String key, long seconds) {
		return SingletonHolder.stringRedisTemplate.expire(key, seconds, TimeUnit.SECONDS);
	}

	// ========== String ==========

	public static String get(String key) {
		return SingletonHolder.stringRedisTemplate.opsForValue().get(key);
	}

	public static void setex(String key, long seconds, String value) {
		SingletonHolder.stringRedisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
	}

	public static boolean setnxex(String key, long seconds, String value) {
		return SingletonHolder.stringRedisTemplate.opsForValue().setIfAbsent(key, value, seconds, TimeUnit.SECONDS);
	}

	public static Long incr(String key) {
		return SingletonHolder.stringRedisTemplate.opsForValue().increment(key, 1);
	}

	public static Long decr(String key) {
		return SingletonHolder.stringRedisTemplate.opsForValue().decrement(key, 1);
	}

	// ========== execute ==========

	public static RedisTemplate<String, Object> redisTemplate() {
		return SingletonHolder.redisTemplate;
	}

	public static StringRedisTemplate stringRedisTemplate() {
		return SingletonHolder.stringRedisTemplate;
	}

	private static class SingletonHolder {
		static final RedisTemplate<String, Object> redisTemplate = SpringContextHolder.getContext().getBean("redisTemplate", RedisTemplate.class);
		static final StringRedisTemplate stringRedisTemplate = SpringContextHolder.getContext().getBean("stringRedisTemplate", StringRedisTemplate.class);
	}

}
